package com.example.demo.msg.aio.server;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

public class ReadHandle implements CompletionHandler<Integer,ByteBuffer> {

    private AsynchronousSocketChannel channel;

    public ReadHandle(AsynchronousSocketChannel channel) {
        this.channel = channel;
    }

    @Override
    public void completed(Integer integer, ByteBuffer buffer) {
        buffer.flip();
        byte[] bytes = new byte[buffer.remaining()];
        buffer.get(bytes);


        try {
            String expression = new String(bytes, "UTF-8");
            System.out.println("服务器收到消息: " + expression);
            String calrResult = "你的消息为:"+expression;
            //向客户端发送消息
            byte[] wriBytes = calrResult.getBytes();

            ByteBuffer wriBff =  ByteBuffer.allocate(wriBytes.length);
            wriBff.put(wriBytes);
            wriBff.flip();
            channel.write(wriBff,wriBff,new WriteHandle(channel));


        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();


        }
    }

    @Override
    public void failed(Throwable throwable, ByteBuffer buffer) {

        try {
            channel.close();
        } catch (IOException e) {

        }

    }
}